<%
/**
 * Tree 组件 - 递归渲染树形结构
 * @param {Array} documents - 文档数组，包含children属性
 * @param {Object} currentDocument - 当前选中的文档，可选
 * @param {String} bookUsername - 书籍所有者用户名
 * @param {String} bookSlug - 书籍slug
 * @param {Number} level - 当前层级，默认为0
 * @param {String} className - 额外的CSS类，可选
 * @param {Boolean} enableContextMenu - 是否启用右键菜单，默认true
 * @param {Boolean} expandAll - 是否展开所有节点，默认false
 * @param {Array} contextMenuItems - 自定义右键菜单项，可选
 * @param {Boolean} autoExpandToCurrent - 是否自动展开到当前文档，默认true
 * @param {Boolean} showStatusBadge - 是否显示状态标签，默认true
 * @param {String} statusField - 状态字段名，默认'status'
 * @param {Boolean} showIcons - 是否显示图标，默认true
 * @param {Object} customIcons - 自定义图标配置，可选
 *   - folder: 文件夹图标
 *   - document: 文档图标
 * @param {String} linkPattern - 链接模式，默认'/document/writer/{username}/{bookSlug}/{docSlug}'
 *   可用占位符：{username}, {bookSlug}, {docSlug}, {docId}
 */

const treeDocuments = typeof documents !== 'undefined' ? documents : [];
const currentDoc = typeof currentDocument !== 'undefined' ? currentDocument : null;
const username = typeof bookUsername !== 'undefined' ? bookUsername : '';
const slug = typeof bookSlug !== 'undefined' ? bookSlug : '';
const currentLevel = typeof level !== 'undefined' ? level : 0;
const extraClass = typeof className !== 'undefined' ? className : '';
const treeEnableContextMenu = typeof enableContextMenu !== 'undefined' ? enableContextMenu : true;
const treeExpandAll = typeof expandAll !== 'undefined' ? expandAll : false;
const treeAutoExpandToCurrent = typeof autoExpandToCurrent !== 'undefined' ? autoExpandToCurrent : true;
const treeShowStatusBadge = typeof showStatusBadge !== 'undefined' ? showStatusBadge : true;
const treeStatusField = typeof statusField !== 'undefined' ? statusField : 'status';
const treeShowIcons = typeof showIcons !== 'undefined' ? showIcons : true;
const treeLinkPattern = typeof linkPattern !== 'undefined' ? linkPattern : '/document/writer/{username}/{bookSlug}/{docSlug}';

// 默认图标配置
const defaultIcons = {
    folder: 'fas fa-folder',
    document: 'fas fa-file-alt'
};

const treeCustomIcons = typeof customIcons !== 'undefined' ? { ...defaultIcons, ...customIcons } : defaultIcons;

const defaultMenuItems = [
    { action: 'add', label: '添加子文档', icon: 'fas fa-plus', className: 'text-gray-700 hover:bg-gray-100' },
    { action: 'edit', label: '编辑文档', icon: 'fas fa-edit', className: 'text-gray-700 hover:bg-gray-100' },
    { action: 'delete', label: '删除文档', icon: 'fas fa-trash', className: 'text-red-600 hover:bg-red-50' }
];

const treeContextMenuItems = typeof contextMenuItems !== 'undefined' ? contextMenuItems : defaultMenuItems;

function getStatusBadge(status) {
    if (!status) return '';
    switch (status) {
        case 'published':
            return '<span class="inline-flex items-center px-2 py-0.5 rounded text-xs font-medium bg-green-100 text-green-800">已发布</span>';
        case 'draft':
            return '<span class="inline-flex items-center px-2 py-0.5 rounded text-xs font-medium bg-yellow-100 text-yellow-800">草稿</span>';
        case 'archived':
            return '<span class="inline-flex items-center px-2 py-0.5 rounded text-xs font-medium bg-gray-100 text-gray-800">已归档</span>';
        default:
            return '<span class="inline-flex items-center px-2 py-0.5 rounded text-xs font-medium bg-blue-100 text-blue-800">' + status + '</span>';
    }
}

function hasChildren(doc) {
    return doc.children && doc.children.length > 0;
}

function isCurrentDocument(doc) {
    return currentDoc && doc.id === currentDoc.id;
}

function hasCurrentDocumentInSubtree(doc) {
    if (!currentDoc || !treeAutoExpandToCurrent) return false;
    if (doc.id === currentDoc.id) return true;
    if (hasChildren(doc)) {
        for (let child of doc.children) {
            if (hasCurrentDocumentInSubtree(child)) {
                return true;
            }
        }
    }
    return false;
}

function shouldExpand(doc) {
    if (treeExpandAll) return true;
    if (treeAutoExpandToCurrent && hasCurrentDocumentInSubtree(doc)) return true;
    return false;
}

function generateDocumentLink(doc) {
    return treeLinkPattern
            .replace('{username}', username)
            .replace('{bookSlug}', slug)
            .replace('{docSlug}', doc.slug)
            .replace('{docId}', doc.id);
}
%>

<div class="tree-container <%= extraClass %>">
    <% if (treeDocuments && treeDocuments.length > 0) { %>
        <% treeDocuments.forEach(function(doc, index) { %>
            <div class="tree-node" data-doc-id="<%= doc.id %>" data-level="<%= currentLevel %>">
                <!-- 文档节点 -->
                <div class="tree-item flex items-center py-2 px-3 transition-colors duration-200 cursor-pointer <%= isCurrentDocument(doc) ? 'bg-blue-500 text-white' : 'hover:bg-gray-50' %>"
                     style="padding-left: <%= currentLevel * 20 + 12 %>px;"
                     data-doc-id="<%= doc.id %>"
                     data-doc-slug="<%= doc.slug %>"
                     data-doc-title="<%= doc.title %>"
                     data-doc-status="<%= doc[treeStatusField] || doc.status || '' %>"
                     data-has-children="<%= hasChildren(doc) %>">

                    <!-- 展开/收起图标 -->
                    <div class="flex-shrink-0 w-4 h-4 mr-3">
                        <% if (hasChildren(doc)) { %>
                            <button class="tree-toggle w-4 h-4 flex items-center justify-center <%= isCurrentDocument(doc) ? 'text-white hover:text-gray-200' : 'text-gray-400 hover:text-gray-600' %> rounded transition-colors duration-150"
                                    data-target="tree-children-<%= doc.id %>"
                                    data-expanded="<%= shouldExpand(doc) ? 'true' : 'false' %>">
                                <i class="fas fa-chevron-right text-xs transition-transform duration-200 <%= shouldExpand(doc) ? 'transform rotate-90' : '' %>"></i>
                            </button>
                        <% } else { %>
                            <div class="w-4 h-4"></div>
                        <% } %>
                    </div>

                    <!-- 文档图标 -->
                    <% if (treeShowIcons) { %>
                        <div class="flex-shrink-0 mr-3">
                            <% if (hasChildren(doc)) { %>
                                <i class="<%= treeCustomIcons.folder %> <%= isCurrentDocument(doc) ? 'text-white' : 'text-blue-500' %> text-sm"></i>
                            <% } else { %>
                                <i class="<%= treeCustomIcons.document %> <%= isCurrentDocument(doc) ? 'text-white' : 'text-gray-400' %> text-sm"></i>
                            <% } %>
                        </div>
                    <% } %>

                    <!-- 文档信息 -->
                    <div class="flex-1 min-w-0">
                        <a href="<%= generateDocumentLink(doc) %>"
                           class="document-link block transition-colors duration-200 <%= isCurrentDocument(doc) ? 'text-white' : 'text-gray-700 hover:text-blue-600' %>"
                           onclick="event.stopPropagation()">

                            <div class="flex items-center space-x-2">
                                <span class="truncate text-sm"><%= doc.title %></span>
                                <span class="text-xs <%= isCurrentDocument(doc) ? 'text-gray-200' : 'text-gray-400' %> flex-shrink-0">(<%= doc.slug %>)</span>
                                <% if (treeShowStatusBadge) { %>
                                    <% const statusValue = doc[treeStatusField] || doc.status || ''; %>
                                    <% if (statusValue) { %>
                                        <div class="flex-shrink-0">
                                            <%- getStatusBadge(statusValue) %>
                                        </div>
                                    <% } %>
                                <% } %>
                            </div>
                        </a>
                    </div>
                </div>

                <!-- 子文档 -->
                <% if (hasChildren(doc)) { %>
                    <div id="tree-children-<%= doc.id %>"
                         class="tree-children <%= shouldExpand(doc) ? '' : 'hidden' %>">
                        <%- include('tree', {
                        documents: doc.children,
                        currentDocument: currentDoc,
                        bookUsername: username,
                        bookSlug: slug,
                        level: currentLevel + 1,
                        enableContextMenu: treeEnableContextMenu,
                        expandAll: treeExpandAll,
                        contextMenuItems: treeContextMenuItems,
                        autoExpandToCurrent: treeAutoExpandToCurrent,
                        showStatusBadge: treeShowStatusBadge,
                        statusField: treeStatusField,
                        showIcons: treeShowIcons,
                        customIcons: treeCustomIcons
                        }) %>
                    </div>
                <% } %>
            </div>
        <% }) %>
    <% } else { %>
        <div class="text-sm text-gray-500 text-center py-8">
            <i class="fas fa-folder-open text-gray-300 text-3xl mb-3 block"></i>
            <div>暂无文档</div>
        </div>
    <% } %>
</div>

<!-- 右键菜单 -->
<% if (currentLevel === 0 && treeEnableContextMenu) { %>
    <div id="treeContextMenu" class="hidden fixed z-50 bg-white border border-gray-200 rounded-lg shadow-lg py-1 min-w-40">
        <% treeContextMenuItems.forEach(function(item) { %>
            <button class="tree-context-item w-full px-4 py-2 text-left text-sm flex items-center space-x-2 transition-colors duration-150 <%= item.className %>"
                    data-action="<%= item.action %>">
                <i class="<%= item.icon %> w-4"></i>
                <span><%= item.label %></span>
            </button>
        <% }) %>
    </div>
<% } %>

<% if (currentLevel === 0) { %>
    <script>
        document.addEventListener('DOMContentLoaded', function () {
            const contextMenu = document.getElementById('treeContextMenu')
            let selectedTreeItem = null

            document.querySelectorAll('.tree-toggle').forEach(toggle => {
                toggle.addEventListener('click', function (e) {
                    e.preventDefault()
                    e.stopPropagation()

                    const targetId = this.dataset.target
                    const target = document.getElementById(targetId)
                    const icon = this.querySelector('i')
                    const isExpanded = this.dataset.expanded === 'true'

                    if (target) {
                        if (isExpanded) {
                            target.classList.add('hidden')
                            icon.classList.remove('rotate-90')
                            this.dataset.expanded = 'false'
                        }
                        else {
                            target.classList.remove('hidden')
                            icon.classList.add('rotate-90')
                            this.dataset.expanded = 'true'
                        }
                    }
                })
            })

            <% if (treeEnableContextMenu) { %>
            document.querySelectorAll('.tree-item').forEach(item => {
                item.addEventListener('contextmenu', function (e) {
                    e.preventDefault()
                    selectedTreeItem = this

                    const menuWidth = 160
                    const menuHeight = 120
                    let x = e.pageX
                    let y = e.pageY

                    if (x + menuWidth > window.innerWidth) {
                        x = window.innerWidth - menuWidth - 10
                    }

                    if (y + menuHeight > window.innerHeight + window.scrollY) {
                        y = window.innerHeight + window.scrollY - menuHeight - 10
                    }

                    x = Math.max(10, x)
                    y = Math.max(10, y)

                    contextMenu.style.left = x + 'px'
                    contextMenu.style.top = y + 'px'
                    contextMenu.classList.remove('hidden')

                    const customEvent = new CustomEvent('treeContextMenuOpen', {
                        detail: {
                            docId: this.dataset.docId,
                            docTitle: this.dataset.docTitle,
                            docSlug: this.dataset.docSlug,
                            docStatus: this.dataset.docStatus,
                            hasChildren: this.dataset.hasChildren === 'true',
                            x: x,
                            y: y,
                            element: this
                        }
                    })

                    document.dispatchEvent(customEvent)
                })
            })

            document.querySelectorAll('.tree-context-item').forEach(item => {
                item.addEventListener('click', function (e) {
                    e.preventDefault()

                    if (!selectedTreeItem) {
                        return
                    }

                    const action = this.dataset.action
                    const docData = {
                        docId: selectedTreeItem.dataset.docId,
                        docTitle: selectedTreeItem.dataset.docTitle,
                        docSlug: selectedTreeItem.dataset.docSlug,
                        docStatus: selectedTreeItem.dataset.docStatus,
                        hasChildren: selectedTreeItem.dataset.hasChildren === 'true'
                    }

                    const customEvent = new CustomEvent('treeAction', {
                        detail: {
                            action: action,
                            ...docData,
                            element: selectedTreeItem
                        }
                    })

                    document.dispatchEvent(customEvent)

                    contextMenu.classList.add('hidden')
                    selectedTreeItem = null
                })
            })

            document.addEventListener('click', function (e) {
                if (contextMenu && !contextMenu.contains(e.target)) {
                    contextMenu.classList.add('hidden')
                    selectedTreeItem = null
                }
            })
            <% } %>
        })
    </script>
<% } %>